/*
**	Anderson Ferminiano
**	contato@andersonferminiano.com -- feel free to contact me for bugs or new implementations.
**	jQuery ScrollPagination
**	28th/March/2011
**	http://andersonferminiano.com/jqueryscrollpagination/
**	You may use this script for free, but keep my credits.
**	Thank you.
*/

(function ($) {
    $.fn.scrollPagination = function (options) {

        var _this = this;
        $(this).removeAttr("scrollpagination");
        if (!$.paginationOptions) {
            $.paginationOptions = {};
        }
        var defaults = new $.fn.scrollPagination.defaults();
        var opts = $.paginationOptions[_this.attr("id")] = $.extend(defaults, options);
        var target = opts.scrollTarget;
        if (target == null) {
            target = obj;
        }
        opts.scrollTarget = target;

        _this.scrollPagination.init(_this, opts);

    };
    $.fn.stopScrollPagination = function () {
        //return this.each(function (index, obj) {
        //    $(obj).attr('scrollPagination', 'disabled');
        //});
        $(this).attr('scrollPagination', 'disabled');
    };

    //var loadStatus = "init";
    $.fn.scrollPagination.loadContent = function (obj, options, firstLoad) {
        var target = options.scrollTarget;
        //var mayLoadContent = $(target).scrollTop() + opts.heightOffset >= $(document).height() - $(target).height();
        var mayLoadContent;
        if (options.container == null) {
            mayLoadContent = $(target).scrollTop() + options.heightOffset > $(document).height() - $(target).height();
        } else {
            mayLoadContent = $(target).scrollTop() + options.heightOffset > options.container.height() - $(target).height()
        }
        if (mayLoadContent) {

            options.loadStatus = "loading";

            if (options.beforeLoad != null) {
                options.beforeLoad(options);
            }

            //$(obj).children().attr('rel', 'loaded');
            //var idx = $(obj).children().size();
            ////$.paginationOptions[obj.attr("id")].contentData["idx"] = idx + 1;

            //if (!options.contentData.page || options.contentData.page < 1) {
            //    $.paginationOptions[obj.attr("id")].contentData.page = 1;
            //}

            var _makeGetRequestUrl = function (url, data) {
                if (data == null) return url;
                var params = /\?/.test(url) ? "&" : "?";
                params += _makeQueryString(data)
                return url + params;
            }

            var _makeQueryString = function (data) {
                var params = new Array();
                for (var key in data) {
                    params.push(key + "=" + data[key]);
                }
                return params.join("&");
            }

            options.contentPage = _makeGetRequestUrl(options.contentPage, options.contentData);

            $.ajax({
                type: 'GET',
                url: options.contentPage,
                //data: options.contentData,
                dataType: "json",
                success: function (data) {
                    if (options.appendItems) {
                        options.appendItems(data);
                    } else {
                        $(obj).append(data);
                    }

                    var objectsRendered = $(obj)[0].querySelectorAll(':not([rel="loaded"])');
                    if (options.afterLoad != null) {
                        options.afterLoad(objectsRendered);
                    }

                    //$.paginationOptions[obj.attr("id")].contentData.page = parseInt(options.contentData.page) + 1;
                    options.loadStatus = "complete";
                }
            });
        }
    };
    $.fn.scrollPagination.init = function (obj, opts) {

        var target = opts.scrollTarget;
        //$(obj).attr('scrollPagination', 'enabled');

        $(target).off("scroll");
        $(target).scroll(function (event) {
            if ($(obj).attr('scrollPagination') != 'disabled') {
                if (opts.loadStatus == "complete") {
                    $.fn.scrollPagination.loadContent($(obj), opts);
                }
            }
        });

        if (opts.loadStatus == "init") {
            $.fn.scrollPagination.loadContent($(obj), opts);
        }
    };
    $.fn.scrollPagination.defaults = function () {
        return {
            'contentPage': null,
            'contentData': {},
            'beforeLoad': null,
            'afterLoad': null,
            'scrollTarget': null,
            'container': null,
            'heightOffset': 0,
            'appendItems': null,
            'dataType': "JSON",
            'loadStatus': "init"
        }
    };
    $.fn.scrollPaginationReload = function () {
        var _this = this;
        var options = $.paginationOptions[_this.attr("id")];
        options.contentData.page = 0;
        options.contentData.idx = 0;
        $(this).html("");
        $.fn.scrollPagination.loadContent(_this, options);
    }
})($);